#include <stdio.h>

/*
	左上: i--, k--	i>=0, k>=0
	右上: i--, k++	i>=0, k<8

	左下: i++, k--	i<8, k>=0
	右下: i++, k++	i<8, k<8
 */

int count = 0;
int run = 0;

int not_danger(int row, int j, int (*chess)[8])
{
    int i, k;
    int flag1, flag2, flag3, flag4, flag5;

    flag1 = flag2 = flag3 = flag4 = flag5 = 0;
    
    // 判断列方向 
    for (i = 0; i < 8; i++) {
        if (*(*(chess + i) + j) != 0) {
            flag1 = 1;
            break;
        }
    }

    // 判断左上方
    for (i = row, k = j; i >= 0 && k >= 0; i--, k--) {
        if (*(*(chess + i) + k) != 0) {
            flag2 = 1;
            break;
        }            
    }

    // 判断右下方
    for (i = row, k = j; i < 8 && k < 8; i++, k++) {
        if (*(*(chess + i) + k) != 0) {
            flag3 = 1;
            break;
        }            
    }

    // 判断右上方
    for (i = row, k = j; i >= 0 && k < 8; i--, k++) {
        if (*(*(chess + i) + k) != 0) {
            flag4 = 1;
            break;
        }            
    }

    // 判断左下方
    for (i = row, k = j; i < 8 && k >= 0; i++, k--) {
        if (*(*(chess + i) + k) != 0) {
            flag5 = 1;
            break;
        }            
    }

    if (flag1 || flag2 || flag3 || flag4 || flag5) {
        return 0;
    }
    else
        return 1;
}

/*
 * row : start row
 * n   : lieshu
 *
 */
void eight_queen(int row, int n, int (*chess)[8])
{
    int chess2[8][8], i, j;

	for (i = 0; i < 8; i++) {
		for (j = 0; j < 8; j++) {
			chess2[i][j] = chess[i][j];
		}
	}

    printf("1th - level : %d Address: %p\n", row, &row);

    if (8 == row) {
        #if 1
        printf("The %d method:\n", count + 1);
        for (i = 0; i < 8; i++) {
            for (j = 0; j < 8; j++) {
                printf("%d ", *(*(chess2 + i) + j));
            }
            printf("\n");
        }
        printf("\n");
        #endif
        count++;
    }
    else {
        for (j = 0; j < n; j++) { // 列 
            if (not_danger(row, j, chess)) {
                for (i = 0; i < 8; i++) {
                    *(*(chess2 + row) + i) = 0; // 整行全部等于0
                }
                *(*(chess2 + row) + j) = 1; // row行j列等于1

                printf("\t\t\t\t row = %d j : %d\n", row, j);                
                eight_queen(row + 1, n, chess2);  

				run++;				
            }
        }
    }
    printf("2th - level : %d Address: %p\n", row, &row);
}

int main()
{
    int chess[8][8] = {0};

	eight_queen(0, 8, chess);

    //printf("count = %d\n", count);
	//printf("run time = %d\n", run);		// 2056 

	return 0;
}
